package cn.tom.config;

import cn.tom.dao.UserMapper;
import cn.tom.entity.Usr;

import java.util.ArrayList;
import java.util.List;

import cn.tom.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component

public class MyUserDetailsService implements UserDetailsService {
    Logger log = LoggerFactory.getLogger(getClass());
    @Autowired(required = false)
    UserMapper userDao;
    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    MailService mailService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("网页的账号:" + username);
        String[] u = username.split(":");
        if (u.length >=2) {
            System.out.println("qqqqqqqqq" + u[1]);
            username = u[1];
        }
        Usr x;
        if ("2".equals(u[0])) {
            // 针对特定情况进行验证码判断，而不是直接从数据库中获取用户信息
            String passwordFromRequest = getPasswordFromRequest(username); // 获取请求中的密码或者验证码
            System.out.println("5555555555" + passwordFromRequest);
            String encodePassword = booleanCaptcha(username, passwordFromRequest); // 进行验证码验证并返回加密验证码
            if (encodePassword == null) {
                throw new CaptchaException("验证码无效");
            }

            System.out.println("匹配成功");
            // 根据特定情况加载用户信息，
            x = userDao.findByEmail(username);
            //String captcha = mailService.getCaptcha(username);
            //String encode = passwordEncoder.encode(captcha);
            x.setPassword(encodePassword);
        } else {
            // 其他情况下，正常从数据库中加载用户信息
            System.out.println("密码登录！");
            x = userDao.findByAccount(username);
            if (x.getPassword().length() <= 6) {
                this.log.info("方便调试， 密码长度不足6， 对明文密码进行加密");
                x.setPassword(this.passwordEncoder.encode(x.getPassword()));
            }
        }
        System.out.println("hhhhhhhh" + x);
        if (x == null) {
            throw new UsernameNotFoundException("账号不存在");
        }

        this.log.info("User=" + x);
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(x.getRole()));
        if (x.getClosed() == 1) {
            return new User(x.getAccount(), x.getPassword(), true, true, true, false, authorities);
        }
        return new User(x.getAccount(), x.getPassword(), authorities);
    }

    private String getPasswordFromRequest(String username) {
        // 从请求中获取密码或者验证码
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 从请求中获取密码或者验证码参数
        String passwordOrVerificationCode = request.getParameter("password");
        // 返回密码或者验证码
        return passwordOrVerificationCode;
    }

    private String booleanCaptcha(String username, String passwordFromRequest) {
        System.out.println("验证码key++++" + username);
        System.out.println("密码++++" +passwordFromRequest);
        // 进行验证码验证的逻辑
        String captcha = mailService.getCaptcha(username);
        System.out.println("验证码啦啦啦啦啦啦啦啦啦啦" +captcha);
        if (passwordFromRequest.equals(captcha)) {
            return passwordEncoder.encode(captcha);
        }
        return null;
    }


}
